package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup>implements SpecGroupService {
    @Autowired
    private SpecGroupService specGroupService;
    @Autowired
    private SpecParamService specParamService;

    //分类查询规格组
    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long id) {

        List<SpecGroupDTO> category_id = SpecGroupDTO.convertEntityList(specGroupService.query()
                .eq("category_id", id).list());
        return category_id;
    }

    //新增规格组
    @Override
    public void saveGroup(SpecGroupDTO groupDTO) {
        specGroupService.save(groupDTO.toEntity(SpecGroup.class));
    }

    //更新规格组
    @Override
    public void updateGroup(SpecGroupDTO groupDTO) {
        specGroupService.updateById(groupDTO.toEntity(SpecGroup.class));
    }

    //
    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(specGroupService.query().eq("category_id", id).list());
        if (groupDTOList.isEmpty()){
            throw new LyException(404,"该规格组不存在");
        }
//        for (SpecGroupDTO specGroupDTO : groupDTOList) {
//            List<SpecParamDTO> params = specGroupDTO.getParams();
//        }
//        return groupDTOList;
        List<SpecParamDTO> paramDTOList = specParamService.querySpecParams(id, null, null);
        Map<Long, List<SpecParamDTO>> map = paramDTOList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        for (SpecGroupDTO groupDTO : groupDTOList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupDTOList;
    }
}
